package com.kangjia.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;

public class DateConverter {

	public static void addConverter(FormatterRegistry registry) {
		registry.addConverter(new DateToString());
		registry.addConverter(new StringToDate());
	}

	private static class DateToString implements Converter<Date, String> {

		public String convert(Date source) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf.format(source);
		}

	}

	private static class StringToDate implements Converter<String, Date> {

		public Date convert(String source) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(source);
			} catch (ParseException e) {
				throw new RuntimeException("ParseException", e);
			}
		}

	}
}
